package com.ht.api.call.func.impl.kf;

import javax.sql.DataSource;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;

import com.ht.api.bean.AjaxResult;
import com.ht.api.bean.LoginBean;
import com.ht.api.call.func.IFunctionCall;
import com.ht.api.constant.KfSessionStatus;
import com.ht.api.db.Db;
import com.ht.api.db.Entity;
import com.ht.api.db.exception.HtException;

import cn.hutool.core.date.DateUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * 结束会话
 * @author asq
 * @createTime 2025年3月17日 10:41:36
 */
@Slf4j
public class KfSessionOverFunctionCall implements IFunctionCall {
	/** 锁 */
	private RedissonClient redissonClient = SpringUtil.getBean(RedissonClient.class);

	@Override
	public String getName() {
		return "结束会话";
	}

	@Override
	public JSONObject execute(LoginBean me, JSONObject param, AjaxResult result) {
		// 获取登陆用户的数据源
		DataSource ds = me.getDataSource();
		
		// 查询会话
		String sessionId = param.getStr("main_id");
		Entity kfSession = Db.createSqlParser("kf_session").findById(ds, sessionId);
		if (kfSession == null) {
			throw new HtException("会话main_id不存在：" + sessionId);
		}
		if (KfSessionStatus.PROGRESS != kfSession.getInt("status")) {
			throw new HtException("只能结束”接待中“的会话！");
		}
		
		// 加锁
		RLock lock = redissonClient.getLock(sessionId);
		if (lock.tryLock()) {
			try {
				// 标记会话状态为“结束会话”
				Entity kfSessionUpdate = Db.createEntity("kf_session");
				kfSessionUpdate.setMainId(sessionId);
				kfSessionUpdate.set("status", KfSessionStatus.OVER);
				Db.insert(ds, kfSessionUpdate);
				
				// 更新会话与客服关联表kf_session_servicer_relation
				Entity kfSessionServicerRelationEntity = Db.createSqlParser("kf_session_servicer_relation")
						.where("session_id", sessionId).order("start_time", "desc").limit(1).findOne(ds);
				if (kfSessionServicerRelationEntity != null) {
					Entity kfSessionServicerRelation = Entity.create("kf_session_servicer_relation");
					kfSessionServicerRelation.setMainId(kfSessionServicerRelationEntity.getMainId());
					kfSessionServicerRelation.set("end_time", DateUtil.now());
					kfSessionServicerRelation.set("status", 1);
					Db.insert(ds, kfSessionServicerRelation);
				}
			} catch (Exception e) {
				log.error("[KfSessionOverFunctionCall]结束会话时发生异常：{}", e.getMessage(), e);
			} finally {
				if (lock.isHeldByCurrentThread()) {
					lock.unlock();
				}}
		} else {
			log.info("[KfSessionOverFunctionCall]未获取到锁，忽略调用。main_id:{}", sessionId);
		}

		return JSONUtil.createObj();
	}

}
